package com.xzsoft.gdwz.ps.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import xz.facade.user.model.Result;

import com.xzsoft.gdwz.model.TrdPsEmInfLog;
import com.xzsoft.gdwz.ps.model.Fj;
import com.xzsoft.gdwz.ps.model.InqOrder;
import com.xzsoft.gdwz.ps.model.InqOrderLine;
import com.xzsoft.gdwz.ps.model.InqVendorHeader;
import com.xzsoft.gdwz.ps.model.InqVendorLine;
import com.xzsoft.gdwz.ps.model.psInqRsult;
import com.xzsoft.gdwz.services.InqOrderService;
import com.xzsoft.gdwz.services.InqVendorService;
import com.xzsoft.gdwz.services.TrdPsEmInfLogService;

/**
 * <p>
 * Title: 远程评审
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Company:兴竹信息
 * </p>
 * 
 * @author:杨 光
 * @date:2016-11-11 上午10:31:29
 */
@Controller
@RequestMapping("/review")
public class ReviewController {

	Logger logger = Logger.getLogger(ReviewController.class);

	@Autowired
	private  InqOrderService inqOrderService;

	@Autowired
	private InqVendorService inqVendorService;
	
	@Autowired
	private TrdPsEmInfLogService trdPsEmInfLogService;

	/**
	 * 远程评审获取询价单
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 *             void
	 */
	@RequestMapping("/getReviewMessage")
	public void getInqOrder(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		response.setCharacterEncoding("UTF-8");

		String createby = request.getParameter("createby");
		String token = request.getParameter("token");
		System.out.println(token);
		Result result = new Result();
		try {
			if (createby == null || "".equals(createby)) {
				result.setResult("");
				result.setResultCode("C0001");
				result.setResultMessage("参数不能为空！");
				result.setSuccess(false);
				JSONObject jb = JSONObject.fromObject(result);
				response.getWriter().println(jb.toString());
				return;
			}
			if (inqOrderService.getCreateby(createby) == null) {
				result.setResult("");
				result.setResultCode("C0002");
				result.setResultMessage("createby参数不合法！");
				result.setSuccess(false);
				JSONObject jb = JSONObject.fromObject(result);
				response.getWriter().println(jb.toString());
				return;
			}
			List<InqOrder> inqlist = new ArrayList<InqOrder>();
			logger.info(inqlist.toString());
			inqlist = inqOrderService.getInqOrder(createby);
			if (inqlist.size() < 1) {
				result.setResult("");
				result.setResultCode("C0003");
				result.setResultMessage("无符合条件的询价单！");
				result.setSuccess(false);
				JSONObject jb = JSONObject.fromObject(result);
				response.getWriter().println(jb.toString());
				return;
			}
			for (int i = 0; i < inqlist.size(); i++) {
				List<InqOrderLine> linelist = new ArrayList<InqOrderLine>();
				List<InqVendorHeader> vendorHeaderlist = new ArrayList<InqVendorHeader>();
				List<Fj> fjlist = new ArrayList<Fj>();
				linelist = inqOrderService.getInqOrderLine(inqlist.get(i)
						.getInqId());
				vendorHeaderlist = inqOrderService.getInqVendorHeader(inqlist
						.get(i).getInqId());
				fjlist = inqOrderService.getFile(inqlist.get(i).getInqId());
				// logger.info("供应商报价行信息"+vendorHeaderlist.toString());
				InqOrder io = new InqOrder();
				io.setInqId(inqlist.get(i).getInqId());
				io.setInqCode(inqlist.get(i).getInqCode());
				io.setInqName(inqlist.get(i).getInqName());
				io.setInqType(inqlist.get(i).getInqType());
				io.setDeliveryDate(inqlist.get(i).getDeliveryDate());
				io.setInqEndDate(inqlist.get(i).getInqEndDate());
				io.setCreateBy(inqlist.get(i).getCreateBy());
				io.setCreateDate(inqlist.get(i).getCreateDate());
				io.setVendorId(inqlist.get(i).getVendorId());
				io.setPayWay(inqlist.get(i).getPayWay());
				io.setCnyCode(inqlist.get(i).getCnyCode());
				io.setInqDesc(inqlist.get(i).getInqDesc());
				io.setInqStatus(inqlist.get(i).getInqStatus());
				io.setTaxRate(inqlist.get(i).getInqStatus());
				io.setTaxRate(inqlist.get(i).getTaxRate());
				io.setIsYq(inqlist.get(i).getIsYq());
				io.setBjCount(inqlist.get(i).getBjCount());
				io.setLimitBj(inqlist.get(i).getLimitBj());
				io.setPurContent(inqlist.get(i).getPurContent());
				io.setPublishDate(inqlist.get(i).getPublishDate());
				io.setReviewMethod(inqlist.get(i).getReviewMethod());
				io.setLimitBjCount(inqlist.get(i).getLimitBjCount());
				io.setYsZje(inqlist.get(i).getYsZje());
				io.setComName(inqlist.get(i).getComName());
				io.setPayRate(inqlist.get(i).getPayRate());
				io.setReCapture(inqlist.get(i).getReCapture());
				JsonConfig jsonConfig = new JsonConfig();
				jsonConfig
						.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
				JSONArray line = JSONArray.fromObject(linelist, jsonConfig);
				io.setOrderLine(line.toString());
				for (int j = 0; j < vendorHeaderlist.size(); j++) {
					InqVendorHeader iv = new InqVendorHeader();
					iv.setInqVendoHid(vendorHeaderlist.get(j).getInqVendoHid());
					iv.setInqId(vendorHeaderlist.get(j).getInqId());
					iv.setVendorId(vendorHeaderlist.get(j).getVendorId());
					iv.setVendorName(vendorHeaderlist.get(j).getVendorName());
					iv.setSumBjPrice(vendorHeaderlist.get(j).getSumBjPrice());
					iv.setSumLimitBjPrice(vendorHeaderlist.get(j).getSumLimitBjPrice());
					List<InqVendorLine> vendorLinelist = new ArrayList<InqVendorLine>();
					vendorLinelist = inqVendorService
							.getInqVendorLine(vendorHeaderlist.get(j)
									.getInqVendoHid());
					JSONArray vendorLine = JSONArray.fromObject(vendorLinelist,
							jsonConfig);
					iv.setInqVendorLine(vendorLine.toString());
					List<Fj> filist = new ArrayList<Fj>();
					filist = inqOrderService.getVendorFile(vendorHeaderlist
							.get(j).getInqId(), vendorHeaderlist.get(j)
							.getVendorId());
					List<Map<String, String>> list = new ArrayList<Map<String, String>>();
					for (int m = 0; m < filist.size(); m++) {
						Map<String, String> map = new HashMap<String, String>();
						String url = "http://219.142.82.143:8080/gdps/xipAttMrgAction.do?method=down&selectedIds="
								+ filist.get(m).getAttId();
						map.put("url", url);
						map.put("classify", filist.get(m).getBusNo());
						map.put("fileid", filist.get(m).getAttId());
						map.put("filename", filist.get(m).getAttFileName());
						map.put("filetype", filist.get(m).getAttFileType());
						map.put("filesize", filist.get(m).getFileSize());
						list.add(map);
					}
					JSONArray vendorfile = JSONArray.fromObject(list,
							jsonConfig);
					iv.setBjFile(vendorfile.toString());
					vendorHeaderlist.set(j, iv);
				}
				JSONArray vendorHeader = JSONArray.fromObject(vendorHeaderlist,
						jsonConfig);
				io.setInqVendorHeader(vendorHeader.toString());
				List<Map<String, String>> list = new ArrayList<Map<String, String>>();
				for (int x = 0; x < fjlist.size(); x++) {
					Map<String, String> map = new HashMap<String, String>();
					String url = "http://219.142.82.143:8080/gdps/xipAttMrgAction.do?method=down&selectedIds="
							+ fjlist.get(x).getAttId();
					map.put("url", url);
					map.put("classify", fjlist.get(x).getBusNo());
					map.put("fileid", fjlist.get(x).getAttId());
					map.put("filename", fjlist.get(x).getAttFileName());
					map.put("filetype", fjlist.get(x).getAttFileType());
					map.put("filesize", fjlist.get(x).getFileSize());
					list.add(map);
				}
				JSONArray listfile = JSONArray.fromObject(list, jsonConfig);
				io.setAttachmentFile(listfile.toString());
				inqlist.set(i, io);
			}
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig
					.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
			JSONArray json = JSONArray.fromObject(inqlist, jsonConfig);
			result.setResult(json.toString());
			result.setResultCode("");
			result.setResultMessage("");
			result.setSuccess(true);
			JSONObject jb = JSONObject.fromObject(result);
			response.getWriter().println(jb.toString());
			logger.info(jb.toString());
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			response.getWriter().flush();
			response.getWriter().close();
		}
	}

	/**
	 * 远程评审更新询价单状态
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/confirmReview")
	public void updateInqOrder(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		String inqId = request.getParameter("inqId");
		Result result = new Result();
		try {
			if (inqId == null || "".equals(inqId)) {
				result.setResult("");
				result.setResultCode("C0001");
				result.setResultMessage("参数不能为空！");
				result.setSuccess(false);
				JSONObject jb = JSONObject.fromObject(result);
				response.getWriter().println(jb.toString());
				return;
			}
			int res = inqOrderService.UpdateInqStatus(inqId);
			if (res > 0) {
				result.setResult("");
				result.setResultCode("C0004");
				result.setResultMessage("成功");
				result.setSuccess(true);
				JSONObject jb = JSONObject.fromObject(result);
				response.getWriter().println(jb.toString());
				return;
			} else {
				result.setResult("");
				result.setResultCode("C0003");
				result.setResultMessage("参数不对");
				result.setSuccess(false);
				JSONObject jb = JSONObject.fromObject(result);
				response.getWriter().println(jb.toString());
				return;
			}
		} catch (IOException e) {
			e.printStackTrace();
			result.setResult("");
			result.setResultCode("C0002");
			result.setResultMessage(e.getMessage());
			result.setSuccess(false);
			JSONObject jb = JSONObject.fromObject(result);
			response.getWriter().println(jb.toString());
			response.getWriter().flush();
			response.getWriter().close();			
			return;
		} finally {
			response.getWriter().flush();
			response.getWriter().close();
		}
	}

	/**
	 * 远程评审接收评审结果
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/reciveResult")
	public void reciveResult(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		response.setCharacterEncoding("UTF-8");
		String resultObj = request.getParameter("psResult");
		JSONObject obj = null;
		Result result = new Result();
		if (resultObj == null || "".equals(resultObj)) {
			result.setResult("");
			result.setResultCode("C0013");
			result.setResultMessage("psResult参数不能为空！");
			result.setSuccess(false);
			JSONObject jb = JSONObject.fromObject(result);
			response.getWriter().println(jb.toString());
			response.getWriter().flush();
			response.getWriter().close();
			return;
		}
		try {
			obj = JSONObject.fromObject(resultObj);
		} catch (Exception e) {
			e.printStackTrace();
			result.setResult("");
			result.setResultCode("C0011");
			result.setResultMessage("psResult格式不正确！");
			result.setSuccess(false);
			JSONObject jb = JSONObject.fromObject(result);
			response.getWriter().println(jb.toString());
			response.getWriter().flush();
			response.getWriter().close();			
			return;
		}
		/*
		 * 保存结果 处理附件
		 */
		try {
			logger.info("obj" + obj.toString());
			psInqRsult resultmap = new psInqRsult();
			// 保存询价单信息
			resultmap.setInqId((String) obj.get("inqId"));
			resultmap.setbProposal((String) obj.get("bProposal")); // 采购建议
			resultmap.setpRdm((String) obj.get("pRdm"));// 配送中心意见
			resultmap.setPsExperts((String) obj.get("psExperts"));// 评审专家
			resultmap.setOrgInqContent((String) obj.get("orgInqContent"));// 中标理由
			inqOrderService.savePsResult(resultmap);
			// 处理附件
			
			JSONArray inqVendorHeader = (JSONArray) obj.get("inqVendorH");
			logger.info("inqVendorHeader" + inqVendorHeader.toString());
			for (int j = 0; j < inqVendorHeader.size(); j++) {
				// 保存询价单报价主信息
				JSONObject objl = (JSONObject) inqVendorHeader.get(j);
				logger.info("objl" + objl.toString());
				psInqRsult map = new psInqRsult();
				map.setInqVendorHid((String) objl.get("inqVendorHid"));
				map.setRownum((String) objl.get("rownum"));
				map.setPsPrice((String) objl.get("psPrice"));
				double businessScore = (Double) objl.get("businessScore");
				double technicalScore = (Double) objl.get("technicalScore");
				double priceScore = (Double) objl.get("priceScore");
				map.setBusinessScore(businessScore);
				map.setTechnicalScore(technicalScore);
				map.setPriceScore(priceScore);
				map.setIsInvalid((String) objl.get("isInvalid"));
				map.setInvalidDesc((String) objl.get("invalidDesc"));
				map.setSumScore((String) objl.get("sumScore"));
				map.setSwdx((String) objl.get("swdx"));
				map.setJsdx((String) objl.get("jsdx"));
				
				if(null==objl.get("inqVendorHid")||"".equals(objl.get("inqVendorHid")))
				{
					continue;
				}				
				inqOrderService.saveInqVendorh(map);
				inqOrderService.saveInqVendorl(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
			e.printStackTrace();
			result.setResult("");
			result.setResultCode("C0014");
			result.setResultMessage(e.getMessage());
			result.setSuccess(false);
			JSONObject jb = JSONObject.fromObject(result);
			response.getWriter().println(jb.toString());
			response.getWriter().flush();
			response.getWriter().close();
			//保存日志
			TrdPsEmInfLog log = new TrdPsEmInfLog();
			log.setId(UUID.randomUUID().toString());
			log.setEmName("YCPS");
			log.setErrorMsg(e.getMessage());
			log.setHasRecieve("0");
			if(e.getMessage().contains("|")){
				String orderId = e.getMessage().split("|")[1];
				log.setOrderId(orderId);
				log.setErrorMsg(e.getMessage().split("|")[0]);
			}
			log.setOrderInfo(obj.toString());
			trdPsEmInfLogService.insertTrdPsEmInfLog(log);
			return;
		}
		/*
		 * 返回正确的结果集
		 */
		result.setResult("");
		result.setResultCode("");
		result.setResultMessage("");
		result.setSuccess(true);
		JSONObject jb = JSONObject.fromObject(result);
		response.getWriter().println(jb.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}
	public static void main(String[] args) {
//		String resultObj ="{'orgInqContent':'综合得分第一','inqId':'eb712e7d-5695-441e-97e0-8c45b5d5e7b9','psExperts':'商务专家：沙波（组长），技术专家：崔磊（组员），朱绪庆（组长）','pRdm':'潍坊百德机械设备有限公司,商务废标，废标原因：未提供业绩，不符合询价文件要求，商务废标。。','inqVendorH':[{'rownum':'1','priceScore':39.92,'swdx':'','sumScore':'97.07','inqVendorHid':'4ABB4DDDF32002A2E0537500520A24C','businessScore':9.4,'jsdx':'','technicalScore':47.75,'psPrice':'50500.00','isInvalid':'0'},{'rownum':'2','priceScore':40,'swdx':'','sumScore':'88.80','inqVendorHid':'4ABAE3D41A4A43CAE0537400520AEA6','businessScore':9.3,'jsdx':'','technicalScore':39.5,'psPrice':'50400.00','isInvalid':'0'},{'rownum':'3','priceScore':23,'swdx':'','sumScore':'71.30','inqVendorHid':'4ACEE0FD884114ECE0537400520AFFB','businessScore':9.3,'jsdx':'','technicalScore':39,'psPrice':'71820.00','isInvalid':'0'},{'rownum':'0','invalidDesc':'未提供业绩，不符合询价文件要求，商务废标。','priceScore':0,'swdx':'','sumScore':'','inqVendorHid':'4ABB4DDDF34202A2E05375A24CE','businessScore':0,'jsdx':'','technicalScore':0,'psPrice':'67200.00','isInvalid':'1'}]}";
//		JSONObject js = JSONObject.fromObject(resultObj);
//		String s = js.getString("inqVendorH");
//		JSONArray jsArray = JSONArray.fromObject(s);
//		for(int i=0;i<jsArray.size();i++){
//			JSONObject objl = jsArray.getJSONObject(i);
//			psInqRsult map = new psInqRsult();
//			map.setRownum(objl.getString("rownum"));
//			System.out.println(objl.getString("rownum"));
//			
//			map.setInqVendorHid( objl.getString("inqVendorHid"));
//			System.out.println(objl.getString("inqVendorHid"));
//			
//			map.setIsInvalid( objl.getString("isInvalid"));
//			System.out.println(objl.getString("isInvalid"));
//			
//			
//			map.setSwdx( objl.getString("swdx").equals("")?"a":objl.getString("swdx"));
//			System.out.println(objl.getString("swdx").equals("")?"a":objl.getString("swdx"));
//			
//			map.setJsdx( objl.getString("jsdx").equals("")?"a":objl.getString("jsdx"));
//			System.out.println(objl.getString("jsdx").equals("")?"a":objl.getString("jsdx"));
//			ReviewController re = new ReviewController();
//			re.inqOrderService.saveInqVendorl(map);
//		}
//		
		
	}
	
}